<template>
  <div>
    <!-- 顶部栏 -->
    <mt-header title="奈雪茶">
      <mt-button slot="left" icon="back" @click="$router.go(-1)"></mt-button>
      <mt-button slot="right">
        <router-link to="/reg" style="color: #fff">注册</router-link>
      </mt-button>
    </mt-header>
    <mt-field
      label="用户名"
      placeholder="请输入用户名"
      v-model="uname"
      :state="nameState"
      @blur.native.capture="checkName"
    ></mt-field>
    <mt-field
      label="密码"
      type="password"
      placeholder="请输入密码"
      v-model="upwd"
      :state="pwdState"
      @blur.native.capture="checkPwd"
    ></mt-field>

    <mt-button @click="login" type="primary" size="large">登录</mt-button>
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex"
export default {
  computed: {
    ...mapState(["user"]),
  },
  data() {
    return {
      uname: "",
      nameState: "", //用于标识用户名输入框的状态
      upwd: "",
      pwdState: "",
    }
  },
  methods: {
    ...mapMutations(["updateUser"]),
    // 验证用户名
    checkName() {
      let exp = /^\w{6,15}$/
      if (exp.test(this.uname)) {
        this.nameState = "success"
        return true
      } else {
        this.nameState = "error"
        return false
      }
    },
    // 验证密码
    checkPwd() {
      let exp = /^\d{6}$/
      if (exp.test(this.upwd)) {
        this.pwdState = "success"
        return true
      } else {
        this.pwdState = "error"
        return false
      }
    },
    // 提交登录-验证表单
    login() {
      if (this.checkName() && this.checkPwd()) {
        const url = "user/login"
        const { uname, upwd } = this
        const params = `unames=${uname}&upwd=${upwd}`
        this.axios.post(url, params).then(res => {
          console.log("登录信息:", res)
          if (res.data.code == 1) {
            this.$dialog
              .alert({
                title: "登录成功!",
                message: "即将跳转主页",
                theme: "round-button",
              })
              .then(() => {
                this.$store.commit("updateUser", res.data)
                console.log("user", this.user)
                this.$router.push("/")
              })
          } else {
            this.$dialog.alert({
              title: "登录失败!",
              message: "账号或密码错误",
            })
          }
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
